package com.lw.oop.dayfive.fdemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: Liu Yuehui
 * @ClassName: ShouPiao
 * @date: 2023/6/15 23:56
 * @description: //TODO 请完善注释信息
 * @version： v1：2023/6/15 23:56：
 **/
public class TicketThread extends Thread{
    private static Integer ticket = 300;

    private Lock lock = new ReentrantLock();

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        do {
            sellTicket();
        } while (ticket > 0);
        //for (int i = 0; i < 50; i++) {
        //    System.out.println(Thread.currentThread().getName()+": " + i);
        //}
    }

    public synchronized void sellTicket(){
        try {

            // 加锁
            //lock.lock();
            if (ticket>0){
                //出票操作
                //使用sleep 模拟一下出票时间
                // yield 主放弃当前线程cpu使用权 ， 然后重新参与cpu使用权的抢夺
                // join 表示加入主线程
                // 让当前线程休息 2 秒 -》 2000毫米奥
                //Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName()+"正在卖票："+ticket--);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 解锁
            //lock.unlock();
        }

    }



    public static void main(String[] args) {

        TicketThread ticket = new TicketThread();

        Thread thread = new Thread(ticket, "窗口1");
        Thread thread1 = new Thread(ticket, "窗口2");
        Thread thread2 = new Thread(ticket, "窗口3");

        thread.start();
        thread1.start();
        thread2.start();
    }

}



